<template>
  <Row :gutter="10">
    <Col :span="2">
      <h5 class="mt-3 mb-1 text-base">资料编码</h5>
      <p>{{ pageData.dataCode }}</p>
      <h5 class="mt-3 mb-1 text-base">资料描述</h5>
      <p>{{ pageData.dataDesc }}</p>
      <div v-show="pageData.videoSourceName">
        <h5 class="mt-3 mb-1 text-base">视频</h5>
        <p>{{ pageData.videoSourceName }}</p>
      </div>
      <div v-show="pageData.warningAudioSourceName">
        <h5 class="mt-3 mb-1 text-base">音频</h5>
        <p>{{ pageData.warningAudioSourceName }}</p>
      </div>
      <div v-show="pageData.pictureSourceName">
        <h5 class="mt-3 mb-1 text-base">图片</h5>
        <p>{{ pageData.pictureSourceName }}</p>
      </div>
      <div v-show="pageData.scrollMessage">
        <h5 class="mt-3 mb-1 text-base">滚动消息</h5>
        <p>{{ pageData.scrollMessage }}</p>
      </div>
    </Col>
    <Col :span="22">
      <div class="modal_table_only">
        <ProTable
          ref="tableRef"
          :fetchListApi="_getProjectDeviceMapV5"
          :columns="columns"
          row-key="deviceId"
          :rowSelection="rowSelection"
        >
          <template #toolbars>
            <Space class="w-full">
              <b-button
                icon="add"
                :disabled="!selectRows.length"
                @click="onAdd()"
                >添加推送列表</b-button
              >
              <b-button icon="detail" @click="pushListVisible = true"
                >查看推送列表</b-button
              >
            </Space>
          </template>
        </ProTable>
      </div>
    </Col>
  </Row>
  <Flex justify="flex-end">
    <Space>
      <Button @click="cancel">取 消</Button>
      <Button :loading="isLoad" type="primary" @click="submitForm"
        >推 送</Button
      >
    </Space>
  </Flex>
  <Modal
    title="设备列表"
    v-model:open="pushListVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <ProTable
      ref="_tableRef"
      :fetchListApi="getPagingData"
      :columns="columns"
      :height="700"
      row-key="deviceId"
      :hide-search="true"
      :rowSelection="_rowSelection"
    >
      <template #toolbars>
        <Space class="w-full">
          <b-button
            icon="delete"
            :disabled="!_selectRows.length"
            @click="onDelete()"
            >删除</b-button
          ></Space
        >
      </template>
    </ProTable>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import {
  Button,
  Col,
  Flex,
  FormItemRest,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Tag,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { listToEnum, listToOption } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import { getModel } from '@/api/device';
import { fetchDictsOfType } from '@/api/dict';
import { getDictType } from '@/api/monitor';
import { saveRecord } from '@/api/notice';
import {
  clickDataPush,
  getProjectDeviceMap,
  pushDataProject,
} from '@/api/push';

const typeEnum: any = ref();
const dictInit = () => {
  getDictType('device_operate_type').then((res) => {
    typeEnum.value = listToEnum(res.data as any, 'dictLabel', 'dictCode');
  });
};

dictInit();

defineOptions({
  name: 'PushConfig',
});

interface Props {
  pageData: any;
}
const props = defineProps<Props>();
const tableRef = ref();
const _tableRef = ref();
const isLoad = ref(false);
const pushListVisible = ref(false);
const sysDeviceModeEnum = ref<Record<string, any>>({});
const sysOnlineStatusEnum = ref<Record<string, any>>({});
const deviceIndustryEnum = ref<Record<string, any>>({});
const modListEnum = ref<Record<string, any>>({});
const modListOption = ref<Global.Option[]>([]);
const projectData = ref([]);
let projectDataAllNum = 0;

const selectRows = ref<any[]>([]);
const rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    selectRows.value = selectedRows;
  },
  preserveSelectedRowKeys: true,
});

const _selectRows = ref<any[]>([]);
const _rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    _selectRows.value = selectedRows;
  },
});

const _getProjectDeviceMapV5 = (params: any) => {
  const projectId = params.projectId?.join() || undefined;
  //   const startVersion = 5;
  //   const endVersion = null;
  return getProjectDeviceMap({
    ...params,
    projectId,
    protobufVersion: '1',
  });
};

const init = () => {
  fetchDictsOfType([
    'sys_device_mode',
    'sys_on_line_status',
    'device_industry',
  ]).then((res: any) => {
    const { sys_device_mode, sys_on_line_status, device_industry } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
    sysOnlineStatusEnum.value = listToEnum(
      sys_on_line_status,
      'dictValue',
      'dictLabel',
    );
    deviceIndustryEnum.value = listToEnum(
      device_industry,
      'dictValue',
      'dictLabel',
    );
  });
  getModel().then((res: any) => {
    modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    modListOption.value = listToOption(res.data, 'model', 'modelId');
  });

  const countProjectNodes = (tree: any) => {
    let count = 0;
    tree.forEach((node: any) => {
      if (node.children && node.children.length > 0) {
        count += countProjectNodes(node.children);
      } else {
        count++;
      }
    });
    return count;
  };
  getProjectData().then((res: any) => {
    projectData.value = res.data;
    projectDataAllNum = countProjectNodes(res.data);
  });
};
init();
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectData.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (omittedValues.length == projectDataAllNum) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    width: 100,
    hideInSearch: true,
    customRender({ record, text }) {
      return `${record.softwareVersion || ''}${record.versionCode ? `(${record.versionCode})` : ''}`;
    },
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    width: 100,
    hideInTable: true,
    customSearchRender(state) {
      return (
        <FormItemRest>
          <Row gutter={8}>
            <Col span={12}>
              <Input
                v-model:value={state.version}
                placeholder='请输入软件版本'
              />
            </Col>
            <Col span={12}>
              <Input
                v-model:value={state.versionCode}
                placeholder='请输入编译版本'
              />
            </Col>
          </Row>
        </FormItemRest>
      );
    },
  },
  {
    title: '固件版本',
    hideInSearch: true,
    dataIndex: 'firmwareVersion',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: { ...sysDeviceModeEnum.value },
    width: 100,
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    valueEnum: { ...modListEnum.value },
    hideInSearch: true,
    width: 150,
  },
  {
    title: '设备型号',
    dataIndex: 'modelIdList',
    hideInTable: true,
    hideInSearch: true,
    customSearchRender(state) {
      return (
        <Select
          max-tag-count={2}
          mode='multiple'
          options={modListOption.value}
          v-model:value={state.modelIdList}
        />
      );
    },
  },

  {
    title: '所属项目',
    dataIndex: 'shortName',
    hideInSearch: true,
  },

  {
    title: '地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
]);

const pushData: any = ref([]);
const emit = defineEmits(['close', 'pushSuccess']);
const onAdd = () => {
  selectRows.value.forEach((item) => {
    if (!pushData.value.includes(item)) {
      pushData.value.push(item);
    }
  });
  message.success('添加成功');
};
const getPagingData = async (params: any) => {
  const { pageNum, pageSize } = params;
  let _data = [];
  if (pushData.value.length <= pageSize) {
    _data = pushData.value;
  } else {
    _data = pushData.value.slice((pageNum - 1) * pageSize, pageNum * pageSize);
  }
  return { rows: _data, total: pushData.value.length };
};
const onDelete = () => {
  for (let i = pushData.value.length - 1; i >= 0; i--) {
    if (_selectRows.value.includes(pushData.value[i])) {
      pushData.value.splice(i, 1);
    }
  }
  _tableRef.value.refresh();
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const submitForm = async () => {
  if (pushData.value.length == 0) {
    message.warning('推送必须将设备添加到推送列表');
    return;
  }
  isLoad.value = true;
  const res = await clickDataPush({
    dataManageId: props.pageData.dataManageId,
  });
  pushData.value.forEach(async (ele: any) => {
    const result = await pushDataProject({
      dataManageId: props.pageData.dataManageId,
      dataPushTotalId: res.data,
      code: ele.deviceCode,
      deviceId: ele.deviceId,
      type: props.pageData.type,
    });
    sleep(() =>
      saveRecordFn(
        ele,
        result,
        '推送',
        JSON.stringify({
          dataManageId: props.pageData.dataManageId,
          dataPushTotalId: res.data,
          code: ele.deviceCode,
          deviceId: ele.deviceId,
        }),
        '/dataPushLog',
      ),
    );
  });

  isLoad.value = false;
  emit('pushSuccess', {
    dataManageId: props.pageData.dataManageId,
    dataPushTotalId: res.data,
    upgradeStatus: '',
  });
};
const cancel = () => {
  emit('close');
};
const saveRecordFn = async (
  item: any,
  res: any,
  operateButton: any,
  requestParam: any,
  operateUri: string,
) => {
  const list = [
    {
      deviceCode: item.deviceCode,
      operateModule: '推送管理/资料管理/图片管理',
      requestParam,
      status: res.code == 200 ? 1 : 0,
      operateButton,
      operateType: typeEnum.value[operateButton],
      operateUri,
    },
  ];
  await saveRecord({ list });
};
</script>
